/**
* @file  Dev
* @author xiao_xie
* @date 2025-03-31
*/


import type { FormProps } from 'antd';
import { Button, Cascader, Checkbox, DatePicker, Form, Input, InputNumber, Radio, Select, Space, Switch } from 'antd';
import { MarginPaddingSize } from '../Container/Dev';
import { useDropComponent } from '../../../../hooks/useDropComponent';
import classNames from 'classnames';
import React, { useMemo } from 'react';
import WrapperComponent from '../WrapperCpmonent';
type FieldType = {
    [key: string]: string; // 允许动态字段名
};

type FormComponentType = {
    type: string
    props: {
        name: string, // 表单属性name
        label?: string, // 表单属性label
        placeholder?: string, // 表单属性placeholder
        options?: any[]
        selectOptions?: any[],
        min?: number, // 表单属性min
        max?: number, // 表单属性max
        maxLength?: number, // 表单属性maxLength
        showCount?: boolean, // 表单属性showCount
        picker?: 'date' | 'week' | 'month' | 'quarter' | 'year';
        showTime?: boolean, // 表单属性showTime
        checkedChildren?: React.ReactNode, // 表单属性checkedChildren
        unCheckedChildren?: React.ReactNode, // 表单属性unCheckedChildren
        disabled?: boolean, // 表单属性disabled
    }
}
type DevProps = {
    children: React.ReactNode;
    accept: Array<string>
    id: number,
    margin?: MarginPaddingSize, // 外边距
    padding?: MarginPaddingSize, // 内边距
    formItemMarginBottem?: MarginPaddingSize, // 表单项底部外边距
    isCenter?: boolean, // 是否居中
}

const componentMap: Record<string, React.ComponentType<any>> = {
    Input,
    Checkbox: Checkbox.Group,
    Radio: Radio.Group,
    Select,
    InputNumber,
    TextArea: Input.TextArea,
    DatePicker,
    Switch,
    Cascader
};


const Dev = ({ id, accept = [''], margin, padding, formItemMarginBottem, children, isCenter }: DevProps) => {
    const { isOver, drop } = useDropComponent(id, accept);
    const [form] = Form.useForm();
    const cls = classNames([
        'w-full  border-solid rounded-md   box-border min-w-[600px]',
        isOver ? 'border-2 border-[#6366F1] border-dashed' : 'border-2 border-transparent',
        margin === MarginPaddingSize.large && 'my-5',
        margin === MarginPaddingSize.medium && 'my-3',
        margin === MarginPaddingSize.small && 'my-1',
        padding === MarginPaddingSize.large && 'p-5',
        padding === MarginPaddingSize.medium && 'p-3',
        padding === MarginPaddingSize.small && 'p-1',
        isCenter && 'flex justify-center items-center'

    ]);

    const formCls = classNames('p-6 flex flex-col',
        formItemMarginBottem === MarginPaddingSize.large && 'gap-5',
        formItemMarginBottem === MarginPaddingSize.medium && 'gap-3',
        formItemMarginBottem === MarginPaddingSize.small && 'gap-1',
    )
    const generateUniqueName = (() => {
        const nameCounts = new Map<string, number>(); // 闭包存储计数器

        return (baseName: string) => {
            const count = (nameCounts.get(baseName) || 0) + 1;
            nameCounts.set(baseName, count);
            return count === 1 ? baseName : `${baseName}_${count}`;
        };
    })();
    const formItems = useMemo(() => {
        const usedNames = new Set<string>();
        return React.Children.map(children, (child: any) => {
            const { props } = child.props.children as FormComponentType;
            const type = child.props.type;
            const label = props.label;;
            const Component = componentMap[type];
            if (!Component) return;
            // Step 1: 获取基础名称
            const baseName = props.name || 'field';

            // Step 2: 生成全局唯一名称
            let uniqueName = generateUniqueName(baseName);

            // Step 3: 处理当前渲染周期内的冲突
            while (usedNames.has(uniqueName)) {
                const match = uniqueName.match(/_(\d+)$/);
                const counter = match ? parseInt(match[1]) + 1 : 2;
                uniqueName = `${baseName.replace(/_(\d+)$/, '')}_${counter}`;
            }

            usedNames.add(uniqueName);
            const componentProps = {
                placeholder: props.placeholder, // 表单属性placeholder
                options: props.options, // 表单属性options
                selectOptions: props.selectOptions, // 表单属性下拉选择器的选项selectOptions
                min: props.min, // 表单属性min
                max: props.max, // 表单属性max
                maxLength: props.maxLength, // 表单属性maxLength
                showCount: props.showCount, // 表单属性showCount
                picker: props.picker, // 表单属性picker
                showTime: props.showTime, // 表单属性showTime
                checkedChildren: props.checkedChildren, // 表单属性checkedChildren
                unCheckedChildren: props.unCheckedChildren, // 表单属性unCheckedChildren
                disabled: props.disabled, // 表单属性disabled
            }
            const {
                showCount,
                showTime,
                checkedChildren,
                unCheckedChildren,
                selectOptions,
                ...safeComponentProps
            } = componentProps;
            return (
                <WrapperComponent
                    key={child.props.id}
                    id={child.props.id}
                    accept={accept} // 允许拖入的组件类型
                >
                    <Form.Item
                        key={`${type}_${uniqueName}`}
                        label={label || uniqueName}
                        name={uniqueName}
                        data-component-id={child.props.id}
                        rules={[{ required: true, message: `请${type === 'Input' ? '填写' : '选择'}` }]}
                    >
                        <Component
                            {...safeComponentProps}
                            // 显式处理需要传递给特定组件的props
                            {...(type === 'TextArea' && { showCount })}
                            {...( (type === 'Select' || type === 'Radio' || type === 'Checkbox') && { options: selectOptions })}
                            {...(type === 'DatePicker' && { showTime })}
                            {...(type === 'Switch' && { checkedChildren, unCheckedChildren })}
                        />
                    </Form.Item></WrapperComponent>
            );

        })

    }, [children])

    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <div className={cls} ref={drop} data-component-id={id}>
            <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                style={{ minWidth: 600 }}
                className={formCls}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                {formItems?.length ? formItems : (
                    <div className="text-center text-gray-500">
                        拖拽表单类组件到这里
                    </div>
                )}
                <Form.Item label={null}>
                    <Space>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                        <Button onClick={() => form.resetFields()}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>

    )
};

export default Dev;
